package com.lngsyz.ywtb.biz.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.lngsyz.ywtb.entity.LoginInfo;
import com.lngsyz.ywtb.entity.source1.GsYwtb;
import com.lngsyz.ywtb.entity.source1.YwtbCityApp;
import com.lngsyz.ywtb.pay.exception.RequestSystemException;
import com.lngsyz.ywtb.redis.RedisUtil;
import com.lngsyz.ywtb.util.CommonUtil;
import com.lngsyz.ywtb.util.HttpUtils;
import com.lngsyz.ywtb.util.StringUtil;
import com.lngsyz.ywtb.util.jwt.TokenUtil;

import net.logstash.logback.encoder.org.apache.commons.lang.StringUtils;
import net.sf.json.JSONObject;

@Service
public class NotLoginService {
    
	@Autowired
	YwtbCityAppService ywtbCityAppService;
	@Autowired
	GsYwtbService gsYwtbService;
	@Autowired
	RedisUtil redisUtil;
	
	public final String UI_PATH = "http://demo.lngsyz.cn";
	
	public final String PRE_TOKEN = "YWTB_TOKEN_";

	/**
	 * 获取token
	 * @param appId
	 * @param appSecret
	 * @return
	 */
    public String getUrl(String appId, String appSecret, String requestId) throws Exception {
    	YwtbCityApp yca = ywtbCityAppService.findByAppId(appId);
    	if(yca != null) {
    		if(StringUtils.equals(appSecret, yca.getSecret())) {
    			// TODO
    			// package LoginInfo
    			LoginInfo loginInfo = packageLoginInfo(requestId, yca.getDistrictCity());
    			loginInfo.setAppId(appId);
    			loginInfo.setDistrictCity(yca.getDistrictCity());
    			// create jwt token
    			String token = TokenUtil.generateToken(loginInfo);
    			String redisKey = CommonUtil.createUuid();
    			redisUtil.set(PRE_TOKEN + redisKey, token, 600);
    			return UI_PATH + "?tokenId=" + redisKey;
    			// return token;
    		} else {
    			throw new RequestSystemException("授权信息有误");
    		}
    	} else {
    		throw new RequestSystemException("授权信息有误");
    	}
    }
    
    private LoginInfo packageLoginInfo(String requestId, String districtCity) throws Exception {
    	if(StringUtils.equals("2102", districtCity)) {
    		// 0:正式  1:测试
    		String dlTest = StringUtil.getConfig("config", "DL_TEST");
    		if(StringUtils.equals("0", dlTest)) {
    			return packageDL(requestId);
    		} else {
    			return packageTest();
    		}
    	} else {
    		return packageTest();
    	}
    }
    
    private LoginInfo packageDL(String requestId) throws Exception {
    	String host = StringUtil.getConfig("config", "DL_URL") + requestId;
		String path = "";
		Map<String, String> headers = new HashMap<String, String>();
		JSONObject bodys = new JSONObject();
		try {
			String postRtn = HttpUtils.doPost(host, path, headers, bodys);
			System.out.println("requestId:" + requestId + "[" + postRtn + "]");
			if(StringUtils.isNotBlank(postRtn)) {
				/*{
				"msg": "请求成功",
				"status": 0,
				"timeStamp": 1701675138723,
				"data": {
					"address": "辽宁省大连经济技术开发区双D港生命三路2-4号",
					"districtCode": "210288",
					"businessId": null,
					"crpName": "靳长征",
					"apPhone": "15641127831",
					"apName": "朱宝义",
					"apCertNo": "232304199407302519",
					"pripid": "21024200101202112163474X",
					"crpCertNo": "210221197501010711",
					"name": "大连乾沣酒店管理有限公司",
					"instCode": "91210242MA7F1G0B2C",
					"crpPhone": "15641127831",
					"createDate": "2021-12-16"
				}
			}*/
				JSONObject postRtnJson = JSONObject.fromObject(postRtn);
				Object dataObj = postRtnJson.containsKey("data") ? postRtnJson.get("data") : null;
				if(dataObj != null) {
					JSONObject dataJson = JSONObject.fromObject(dataObj);
					LoginInfo rtn = new LoginInfo();
					rtn.setBusinessId(dataJson.containsKey("businessId") ? dataJson.getString("businessId") : "");
					rtn.setPripid(dataJson.containsKey("pripid") ? dataJson.getString("pripid") : "");
					rtn.setName(dataJson.containsKey("name") ? dataJson.getString("name") : "");
					rtn.setAddress(dataJson.containsKey("address") ? dataJson.getString("address") : "");
					rtn.setInstCode(dataJson.containsKey("instCode") ? dataJson.getString("instCode") : "");
					rtn.setCrpName(dataJson.containsKey("crpName") ? dataJson.getString("crpName") : "");
					rtn.setCrpCertNo(dataJson.containsKey("crpCertNo") ? dataJson.getString("crpCertNo") : "");
					rtn.setCrpPhone(dataJson.containsKey("crpPhone") ? dataJson.getString("crpPhone") : "");
					rtn.setApName(dataJson.containsKey("apName") ? dataJson.getString("apName") : "");
					rtn.setApCertNo(dataJson.containsKey("apCertNo") ? dataJson.getString("apCertNo") : "");
					rtn.setApPhone(dataJson.containsKey("apPhone") ? dataJson.getString("apPhone") : "");
					rtn.setDistrictCode(dataJson.containsKey("districtCode") ? dataJson.getString("districtCode") : "");
					String createDate = dataJson.containsKey("createDate") ? dataJson.getString("createDate") : "";
					rtn.setCreateDate(CommonUtil.strToDateShort(createDate));
					return rtn;
				} else {
					throw new RequestSystemException("无法获取当前企业信息");
				}
			} else {
				throw new RequestSystemException("无法获取当前企业信息");
			}
		} catch(Exception e) {
			throw new RequestSystemException("无法获取当前企业信息");
		}
    }
    
    private LoginInfo packageTest() {
    	List<GsYwtb> gsYwtbs = gsYwtbService.findByBusinessLicense("91210211MA10TNLN1A");
		if(gsYwtbs != null && gsYwtbs.size() > 0) {
			GsYwtb gsYwtb = gsYwtbs.get(0);
			LoginInfo rtn = new LoginInfo();
			rtn.setBusinessId(gsYwtb.getBusinessId());
			rtn.setPripid(gsYwtb.getPripid());
			rtn.setName(gsYwtb.getName());
			rtn.setAddress(gsYwtb.getAddress());
			rtn.setInstCode(gsYwtb.getInstCode());
			rtn.setCrpName(gsYwtb.getCrpName());
			rtn.setCrpCertNo(gsYwtb.getCrpCertNo());
			rtn.setCrpPhone(gsYwtb.getCrpPhone());
			rtn.setApName(gsYwtb.getApName());
			rtn.setApCertNo(gsYwtb.getApCertNo());
			rtn.setApPhone(gsYwtb.getApPhone());
			rtn.setDistrictCode(gsYwtb.getDistrictCode());
			rtn.setCreateDate(gsYwtb.getCreateDate());
			return rtn;
		} else {
			throw new RequestSystemException("无法获取当前企业信息");
		}
    }
    
    public LoginInfo decodeLoginInfoByToken(String token) {
    	LoginInfo loginInfo = TokenUtil.getUserInfoFromToken(token);
    	return loginInfo;
    }
    
    public String getToken(String tokenId) {
    	String tokenKey = PRE_TOKEN + tokenId;
    	String token = redisUtil.hasKey(tokenKey) ? redisUtil.get(tokenKey).toString() : "";
    	redisUtil.del(tokenKey);
    	return token;
    }
}
